package be.kuleuven.peno3.mobiletoledo.view.messages;

import java.util.GregorianCalendar;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import be.kuleuven.peno3.mobiletoledo.R;
import be.kuleuven.peno3.mobiletoledo.Data.Client.MessagesClient;
import be.kuleuven.peno3.mobiletoledo.model.User;

public class Send extends Activity {
	private Button submit;
	private EditText bodytxt, titletxt;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sendmessage);
		
		TextView bar = (TextView) findViewById(R.id.send_msg_bar);
		bar.setText("Bericht versturen");
		bodytxt=(EditText) findViewById(R.id.messagebodyedit);
		titletxt = (EditText) findViewById(R.id.messagetitleedit);
		submit=(Button) findViewById(R.id.sendmessage);
		
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String title = titletxt.getText().toString();
				String body = bodytxt.getText().toString();
				
				if(body.length()==0 || title.length()==0) {
					Toast.makeText(Send.this.getApplicationContext(), "Gelieve alle velden in te vullen", Toast.LENGTH_SHORT).show();
					return;
				}
				
				int course_id;
				try {
					course_id = Send.this.getIntent().getExtras().getInt("course_id");
				} catch (NullPointerException e) {
					course_id=0;
				}
				
				if(User.getInstance().getUsername()!=null && User.getInstance().getUsername().length()!=0) {
					if(!MessagesClient.addMessage(title, body, User.getInstance().getUsername(), course_id, new GregorianCalendar())) {
						Toast.makeText(Send.this.getApplicationContext(), "Er is geen internetverbinding", Toast.LENGTH_SHORT).show();
						finish();
					}
				}
				else {
					Toast.makeText(Send.this.getApplicationContext(), "Je hebt geen gebruikersnaam ingegeven.", Toast.LENGTH_SHORT).show();
				}
				
				//exit the Activity
				try {
					finish();
				} catch (Throwable e) {
					e.printStackTrace();
				}
			}
		});
	}
}
